package JUC.UnSafeDemo;

import lombok.Data;
import lombok.ToString;
import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author CKC
 * @DateTime 2021/6/8 15:14
 */
public class UnSafeDemo {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        //Unsafe 对象提供了非常底层的，操作内存、线程的方法，Unsafe 对象不能直接调用，只能通过反射获得
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);
        Unsafe unsafe = (Unsafe) theUnsafe.get(null);

        System.out.println(unsafe);

        // 1.获取域的偏移地址
        long IdOffset = unsafe.objectFieldOffset(Teacher.class.getDeclaredField("id"));
        long nameOffset = unsafe.objectFieldOffset(Teacher.class.getDeclaredField("name"));

        Teacher t = new Teacher();
        //2.执行Cas操作
        unsafe.compareAndSwapInt(t, IdOffset, 0, 1);
        unsafe.compareAndSwapObject(t, nameOffset, null, "张三");

        //3.验证
        System.out.println(t.toString());


    }
}

@Data
@ToString
class Teacher {
    volatile int id;
    volatile String name;
}
